awk -v定义变量

参数:-v 定义变量,变量可以是常量或引用外置变量,

语法 : awk -v 变量名=常量或外置变量

如下:查找aaa所在行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#查看1.txt
[root@ffing_fun test]# cat 1.txt
aaa  bbb
xxx yyy

#定义外置变量
LINE_VAR=aaa

#-v定义内置变量名var1,应用$LINE_VAR的外置变量,打印第2列等于var1的行
[root@ffing_fun test]# cat -n 1.txt|awk -v var1=$LINE_VAR  '$2==var1 {print}'
     1  aaa  bbb
#获取行号
[root@ffing_fun test]# cat -n 1.txt|awk -v var1=$LINE_VAR  '$2==var1 {print}'|awk '{print $1}'
1



###############
#常量,第2列==aaa,常量需要双引号
[root@ffing_fun test]# cat -n 1.txt|awk   '$2=="aaa"  {print}'|awk '{print $1}'
1


#若变量中有空格也需要使用双引号
[root@localhost test]# cat /root/test/temp/b.sh/hostgroup_list_id.txt 
Linux Server:19
JGJ:20
tb best:21
aaa:25
a:22
b:11111
b b:23
c:24
[root@localhost test]# AAA='b b'
[root@localhost test]# cat /root/test/temp/b.sh/hostgroup_list_id.txt |awk -v var="$AAA" -F ':'  '$1==var '{print}''
b b:23

指定输出分隔符

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[root@FFing ~]# cat test.txt 
sample1,male,12
sample2,female,23
sample3,male,15
sample4,female,28
#替换输出分隔符将半角逗号换成tab
[root@FFing ~]#cat 1.txt|awk -F ',' -v OFS='\t' '{$1=null;print}'
        male    12
        female  23
        male    15
        female  28